
<template>
  <div class="component-editor-wrapper">
    <div class="component-editor-tool-bar-wrapper">
      <div ref="toolbar" class="component-editor-tool-bar"></div>
      <div class="component-editor-action">
        <span class="editor-action-btn">
          <el-dropdown :show-timeout="0" @command="selectModule">
            <span class="el-dropdown-link">
              {{currentModule? currentModule: '选择板块'}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="moduleItem in modules" :key="moduleItem.id" :command="moduleItem">{{moduleItem.sectionName}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
        <span class="editor-action-btn">
          <el-dropdown :show-timeout="0" @command="selectSection">
            <span class="el-dropdown-link">
              {{currentSection? currentSection: '选择栏目'}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="section in sections" :key="section.id" :command="section">{{section.sectionName}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
        <span class="editor-action-btn">
          <el-dropdown :show-timeout="0" @command="selectProject">
            <span class="el-dropdown-link">
              {{currentProject? currentProject: '选择课题'}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="project in projects" :key="project.id" :command="project">{{project.sectionName}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
        <el-button v-if="article.articleStatus === '1'" type="primary" style="padding:5px 14px;" @click="save(0)">取消发布并保存</el-button>
        <el-button v-if="article.articleStatus === '1'" type="primary" style="padding:5px 14px;" @click="save(1)">保存并发布</el-button>
        <el-button v-if="article.articleStatus === '0'" type="primary" style="padding:5px 14px;" @click="save(0)">保存草稿</el-button>
        <el-button v-if="article.articleStatus === '0'" type="primary" style="padding:5px 14px;" @click="save(1)">保存并发布</el-button>
        <el-button style="padding:5px 14px;" @click="$emit('close')">关闭</el-button>
      </div>
    </div>
    <div class="component-editor-main">
      <div class="component-title-input">
        <input type="text" placeholder="请输入文章标题..." v-model="article.articleTitle">
      </div>
      <div class="component-editor" ref="editor"></div>
      <div class="component-add-file">
        <el-upload
          class="upload-demo"
          :action="$http.adornUrl('/fileUpload')"
          :on-success="addToArticle"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :on-progress="beforeAvatarUpload"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :headers = "headers"
          :file-list="article.articleAttachment">
          <el-button style="position:absolute;top: 10px;" size="small" type="primary">上传附件</el-button>
        </el-upload>
      </div>
      <div class="component-ccList">
        <div @click="selectDingUsers()" class="select-btn"><span><i class="el-icon-plus"></i></span>抄送</div>
        <div class="select-btn" v-for="(item, index) in ccIds" :key="item.index" style="padding-left:0;">
          {{ccNames[index]}}
          <div class="del" @click="delMember(index)">移除</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
    import sinaEmotions from '@/assets/emotion/sina'
    import dingMixin from  '@/mixins/ding'
    import formUtil from '@/utils/formUtil'

    export default {
      name: 'editor',
      data () {
        return {
          headers: {
            token: this.$cookie.get('token')
          },
          article: {
            sectionId: '',
            articleTitle: '',
            articleMasterId: '',
            articleMasterName: '',
            articleInfo: '',
            articleContent: '',
            articleFrom: 0,
            articleRange: 0,
            articleReaderid: '',
            articleStatus: '0',
            articleAttachment: [],
            articleCcId: '',
            articleCcName: '',
            articleDatatype: ''
          },
          formVerify: {
            articleTitle: '请输入标题',
            sectionId: '请选择板块和栏目'
          },
          currentModule: '',
          currentModuleId: '',
          currentSection: '',
          currentSectionId: '',
          currentProject: '',
          currentPeojectId: '',
          sections: [],
          modules: [],
          projects: [],
          ccIds: [],
          ccNames: [],
          editor: null,
          isModuleManager: false,
          isSectionManager: false
        }
      },
      mixins: [dingMixin],
      props: ['showEditor', 'articleId'],
      methods: {
        handleRemove(file, fileList) {
          let idx = this.article.articleAttachment.findIndex(item => item.uid === file.uid);
          if(idx >= 0) this.article.articleAttachment.splice(idx,1);
        },
        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        selectDingUsers() {
          this.complexPicker(20, [], this.ccIds).then(
            data => {
              this.ccIds = data.map(item => item.emplId);
              this.ccNames = data.map(item => item.name);
            }
          );
        },
        delMember(index) {
          this.ccIds.splice(index,1);
          this.ccNames.splice(index,1);
        },
        async selectModule(e) {
          this.currentModule = e.sectionName;
          this.currentModuleId = e.id;
          this.article.articleDatatype = e.id;
          this.currentSection = '';
          this.currentSectionId = '';
          this.article.sectionId = '';
          this.sections = await this.$httpN.postQ('community/section/list', {'parentid': e.id});
          let isModuleManager = false;
          this.modules.forEach((moduleItem) => {
            if(moduleItem.id === e.id){
              let managerArr = moduleItem.sectionManageUserid.split(',');
              isModuleManager = managerArr.includes(this.userInfo.dingId);
            }
          })
          this.isModuleManager = isModuleManager;
          if(this.sections.length >0 ){
            this.sections = this.sections.filter((item) => {
              if(item.sectionPublisher !== '') {
                let managerArr = item.sectionManageUserid.split(',');
                let userArr = item.sectionPublisher.split(',');
                if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || isModuleManager) {
                  return true;
                }else {
                  return userArr.includes(this.userInfo.dingId);
                }
              }else{
                return true;
              }
            })
          }
        },
        async selectSection(e) {
          this.currentSection = e.sectionName;
          this.currentSectionId = e.id;
          this.article.sectionId = e.id;
          this.currentProject = '';
          this.currentProjectId = '';
          this.projects = await this.$httpN.postQ('community/section/list', {'parentid': e.id});
          let isSectionManager = false;
          this.sections.forEach((moduleItem) => {
            if(moduleItem.id === e.id){
              let managerArr = moduleItem.sectionManageUserid.split(',');
              isSectionManager = managerArr.includes(this.userInfo.dingId);
            }
          })
          this.isSectionManager = isSectionManager;
          if(this.projects.length >0 ){
            this.projects = this.projects.filter((item) => {
              if(item.sectionPublisher !== '') {
                let managerArr = item.sectionManageUserid.split(',');
                let userArr = item.sectionPublisher.split(',');
                if(item.sectionRange === '0' || managerArr.includes(this.userInfo.dingId) || isSectionManager || isModuleManager) {
                  return true;
                }else {
                  return userArr.includes(this.userInfo.dingId);
                }
              }else{
                return true;
              }
            })
          }
        },
        async selectProject(e) {
          this.currentProject = e.sectionName;
          this.currentPeojectId = e.id;
          this.article.sectionId = e.id;
        },
        addToArticle(response, file, fileList) {
          if(response.code === 0) {
            this.article.articleAttachment.push({
              name: file.name,
              url: response.url
            })
          }
        },
        beforeAvatarUpload(event, file, fileList){
          let loadProgress = Math.floor(event.percent) //这就是当前上传的进度
          if(file.status === 'uploading' && event.percent === 100){
            event.percent = 99 
          }
        },
        async save(status) {
          if(this.currentProject === '') return this.$message.error('请选择课题')
          this.article.articleContent = this.editor.txt.html();
          this.article.articleInfo = this.editor.txt.text().replace(/&nbsp;/g, '');
          this.article.articleTitle = this.article.articleTitle.trim();
          if(!formUtil.verifyData(this.article, this.formVerify)) return;
          if(this.article.articleTitle.length > 30) return this.$message.error('标题长度不能超过30个字')
          this.article.articleStatus = status;
          if(this.ccIds.length > 0) {
            this.article.articleCcId = this.ccIds.join(',');
            this.article.articleCcName = this.ccNames.join(',');
          }
          if(this.articleId) {
            if(!await this.$httpN.postB('community/article/update', this.article)) return;
            formUtil.submitSuccess('编辑成功');
            this.$emit('close');
          }else {
            if(!await this.$httpN.postB('community/article/save', this.article)) return;
            formUtil.submitSuccess('创建成功');
            this.$emit('close');
          }
        },
        beforeUpload(file) {
          const isNotEmpty = file.size > 0;
          const isLt2M = file.size / 1024 / 1024 < 20;

          if (!isNotEmpty) {
            this.$message.error('上传的文件内容不能为空');
          }
          if (!isLt2M) {
            this.$message.error('上传单个文件大小不能超过20MB!请压缩文件');
          }

          return isNotEmpty && isLt2M;
        }
      },
      async mounted() {
        if(this.articleId) {
          let article = await this.$httpN.get('community/article/info/' + this.articleId);
          article.articleAttachment = JSON.parse(article.articleAttachment);
          this.article = article;
          this.sections = await this.$httpN.postQ('community/section/list', {'parentid': this.article.plateId});
          if(this.article.secondSectionId) {
            this.projects = await this.$httpN.postQ('community/section/list', {'parentid': this.article.firstSectionId});
            this.currentModule = this.article.plateName;
            this.currentSection = this.article.firstSectionName;
            this.currentProject = this.article.secondSectionName;
          }else{
            this.currentModule = this.article.plateName;
            this.currentSection = this.article.firstSectionName;
          }
          this.ccIds = article.articleCcId === '' ? []: article.articleCcId.split(',');
          this.ccNames = article.articleCcName === '' ? []: article.articleCcName.split(',');
        }else {
          this.article.articleMasterId = this.userInfo.dingId;
          this.article.articleMasterName = this.userInfo.realName;
        }
        this.modules = await this.$httpN.postQ('community/section/list', {'parentid': null})
        this.$nextTick(() => {
          let E = window.wangEditor;
          if(this.$refs.toolbar) {
            var editor = new E(this.$refs.toolbar, this.$refs.editor)
            editor.customConfig.uploadImgServer = this.$http.adornUrl('/fileUpload');
            editor.customConfig.uploadImgHeaders = {'token': this.$cookie.get('token')}
            editor.customConfig.uploadFileName = 'file'
            editor.customConfig.pasteTextHandle = function (content) {
              let handleData = content;
              //清除无用标签
              handleData = handleData.replace(/<(meta|script|link|html|head|)[^>]*>/, '');
              handleData = handleData.replace(/<\/(meta|script|link|html|head)[^>]*>/, '');
              handleData = handleData.replace(/<head>[\s\S]*<body lang=ZH-CN>/, '');
              handleData = handleData.replace(/style\s*?=\s*?(['"])[\s\S]*?\1/g, '');
              handleData = handleData.replace(/\sclass\s?=\s?\w*/g, '');
              handleData = handleData.replace(/<span\s*?lang=EN-US\s*?><o:p><\/o\:p><\/span>/g, '');
              handleData = handleData.replace(/lang=EN-US/g, '');
              handleData = handleData.replace(/\n/g, '');
              return handleData
            }
            editor.customConfig.menus = ['head','bold','fontSize','fontName','table', 'italic','underline','strikeThrough','foreColor','backColor','link','justify','quote','emoticon','image','video','code','undo','redo']
            editor.customConfig.uploadImgHooks = {
              customInsert: function (insertImg, result, editor) {
                var url = result.url + '?x-oss-process=style/forbid'
                insertImg(url)
              }
            }
            editor.customConfig.emotions = [{title:'默认',type: 'image',content: sinaEmotions}]
            editor.create();
            this.editor = editor;
            if(this.articleId) editor.txt.html(this.article.articleContent);
          }
        })
      }
    }
</script>

<style lang="scss">
  .component-editor-wrapper{
    background:#D9D9D9;
    height: 100%;
    width: 100%;
    position: fixed;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1099;
    .component-editor-tool-bar-wrapper{
      padding: 7px 0;
      border-bottom: 1px solid #ccc;
      position: relative;
      .component-editor-action{
        height: 100%;
        position: absolute;
        right: 20px;
        top:0;
        padding: 8px 0;
        .editor-action-btn{
          color: #999;
          padding: 0 5px;
          font-size: 14px;
          cursor: pointer;
          &:hover{
            color: black;
          }
          .el-dropdown-link {
            cursor: pointer;
            color: #999;
            &:hover{
              color: black;
            }
          }
        }
      }
    }
    .component-editor-main{
      width: 980px;
      margin: 40px auto 0;
      height: calc(100% - 120px);
      box-shadow: 0 20px 20px rgba(0,0,0,.1);
      background:white;
      .component-title-input{
        height: 60px;
        border-bottom: 1px solid #d9d9d9;
        input{
          width: 100%;
          height: 100%;
          border: none;
          outline: none;
          font-size: 30px;
          font-weight: 400;
          padding: 0 30px;
          color:#606266;
        }
      }
      .component-editor{
        height: calc(100% - 154px); 
        .w-e-text{
          overflow-y: auto;
        }
        border-bottom: 1px solid #d9d9d9;
      }
      .component-add-file{
        height: 54px;
        overflow: auto;
        border-bottom: 1px solid #d9d9d9;
        padding: 10px;
        position: relative;
        .el-upload-list{
          vertical-align: middle;
          display:inline-block;
          padding-left: 90px;
        }
        .el-upload-list__item{
          display:inline-block;
          width: auto;
          margin-top: 0;
          margin-right: 10px;
        }
        .el-upload-list__item-name{
          margin-right: 30px;
        }
      }
      .component-ccList{
        height: 40px;
        padding: 5px;
        overflow: auto;
        background: white;
        .select-btn{
          margin-bottom:5px;
          float:left;
          font-weight: normal;
          margin-right: 5px;
          width: 80px;
          height: 28px;
          border-radius: 30px;
          background: #FAFAFA;
          border: 1px solid #ECECEC;
          position: relative;
          padding-left: 21px;
          line-height: 28px;
          color: #7982A7;
          font-size: 12px;
          text-align: center;
          cursor: pointer;
          span{
            position: absolute;
            top: 1px;
            left: 1px;
            display:block;
            height: 24px;
            width: 24px;
            background: #CACACA;
            color: white;
            border-radius: 50%;
            text-align: center;
            line-height: 24px;
            img{
              width: 24px;
              height: 24px;
              border-radius: 50%;
            }
          }
          .del{
            position: absolute;
            top:0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 30px;
            color: white;
            text-align: center;
            background:rgba(130, 130, 130, 0.9);
            display: none;
          }
          &:hover{
            .del{
              display: block;
            }
          }
        }
      }
    }
  }
  @media screen and (max-width: 1120px) {
    .component-editor-wrapper .component-editor-tool-bar-wrapper .component-editor-action{
      top: 40px;
      left: 5px;
    }
  }
</style>